package com.xukun.changgou.auth.schedule;

import com.xukun.changgou.common.constants.CommonConstant;
import com.xukun.changgou.common.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author xukun
 * @Date 2021-06-06 14:26
 * @Description 清除redis中的token白名单定时器，12个小时执行一次
 */
@Component
@EnableAsync
@EnableScheduling
public class ClearTokenSchedule {

    private Logger logger = LoggerFactory.getLogger(ClearTokenSchedule.class);

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 该定时任务主要用与删除数据库中没有关联的图片以及删除关联的磁盘上的图片
     */
    @Scheduled(cron = "0 0 4 * * ?")//每天凌晨4点执行一次
    public void scheduledTaskDown() {
        if (redisUtil.hasKey(CommonConstant.REDIS_TOKEN_BLACK_LIST)) {
            Date nowDate = new Date();
            String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nowDate);
            logger.info("===============定时任务【清除无效Token】开始：" + nowTime + "===============");

            List<String> deletedList = new ArrayList<>();
            Long len = redisUtil.lLen(CommonConstant.REDIS_TOKEN_BLACK_LIST);
            for (int i = 0; i < len; i++) {
                String expire = redisUtil.lIndex(CommonConstant.REDIS_TOKEN_BLACK_LIST, i).split("\\|")[1];
                if (Long.valueOf(expire) < nowDate.getTime()) {
                    //由于不能直接遍历删除，所以先将过期的token保存在列表中
                    deletedList.add(redisUtil.lIndex(CommonConstant.REDIS_TOKEN_BLACK_LIST, i));
                }
            }
            //删除无效的token
            deletedList.forEach(token -> redisUtil.lRemove(CommonConstant.REDIS_TOKEN_BLACK_LIST, 0, token));
            logger.info("===============定时任务【清除无效Token】结束：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "===============");
        }
    }

}
